package com.hzcx.app.simplechat.chat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.util.Pair;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMLocationMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.api.BaseDialogObserver;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.base.BaseLoadingDialog;
import com.hzcx.app.simplechat.bean.UpLoadImgBean;
import com.hzcx.app.simplechat.chat.bean.SendImgBean;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.model.PublicModel;
import com.hzcx.app.simplechat.ui.chat.ChatActivity;
import com.hzcx.app.simplechat.ui.chat.ChatSearchImgActivity;
import com.hzcx.app.simplechat.ui.chat.bean.GdMapPoiBean;
import com.hzcx.app.simplechat.ui.chat.contract.ChatContract;
import com.hzcx.app.simplechat.ui.main.MainActivity;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.down.DownLoadUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.file.FileUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.util.token.TokenUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import eason.linyuzai.download.ELoad;
import eason.linyuzai.download.recycle.TaskRecycler;
import eason.linyuzai.download.task.DownloadTask;
import io.reactivex.Observable;
import okhttp3.ResponseBody;


/**
 * 环信聊天相关工具类
 */
public class ChatUtil {

    public static ChatUtil chatUtil = null;

    public static ChatUtil getInstance() {
        if (chatUtil == null) {
            chatUtil = new ChatUtil();
        }
        return chatUtil;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        EMOptions options = new EMOptions();
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        // 是否自动将消息附件上传到环信服务器，默认为True是使用环信服务器上传下载，如果设为 false，需要开发者自己处理附件消息的上传和下载
        options.setAutoTransferMessageAttachments(true);
        // 是否自动下载附件类消息的缩略图等，默认为 true 这里和上边这个参数相关联
        options.setAutoDownloadThumbnail(true);
        // 设置是否需要已读回执
        options.setRequireAck(true);
        // 设置是否需要送达确认
        options.setRequireDeliveryAck(true);
        //初始化
        EMClient.getInstance().init(context, options);
        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(true);
    }

    /**
     * 登出
     */
    public void logOut() {
        EMClient.getInstance().logout(true);
    }

    /**
     * 登录环信
     *
     * @param userName
     * @param pwd
     */
    public void login(String userName, String pwd, EMCallBack callBack) {
        EMClient.getInstance().login(userName, pwd, callBack);
    }

    /**
     * 加载初始化数据
     */
    public void loadGroupDate() {
        EMClient.getInstance().groupManager().loadAllGroups();
        EMClient.getInstance().chatManager().loadAllConversations();
    }

    /**
     * change the chat type to EMConversationType
     *
     * @param chatType
     * @return
     */
    public static EMConversation.EMConversationType getConversationType(int chatType) {
        if (chatType == ChatConstant.CHATTYPE_SINGLE) {
            return EMConversation.EMConversationType.Chat;
        } else if (chatType == ChatConstant.CHATTYPE_GROUP) {
            return EMConversation.EMConversationType.GroupChat;
        } else {
            return EMConversation.EMConversationType.ChatRoom;
        }
    }

    /**
     * 插入删除消息
     *
     * @param toChatUsername
     * @param receiveId
     * @param receiveName
     * @param messageStatusCallback
     */
    public void insertDeleteMessage(EMConversation conversation, String toChatUsername, int receiveId, String receiveName, EMCallBack messageStatusCallback) {
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        EMCustomMessageBody customBody = new EMCustomMessageBody(ChatConstant.EXTRA_CUSTOM_DELETE);
        message.addBody(customBody);
        message.setTo(toChatUsername);
        message.setAttribute(ChatConstant.EXTRA_SEND_USER_ID, UserInfoUtil.getUserId());
        message.setAttribute(ChatConstant.EXTRA_SEND_USER_NICKNAME, UserInfoUtil.getUserNickName());
        message.setAttribute(ChatConstant.EXTRA_RECEIVE_USER_ID, receiveId);
        message.setAttribute(ChatConstant.EXTRA_RECEIVE_USER_NICKNAME, receiveName);
        conversation.insertMessage(message);
    }

    /**
     * 发送文本消息
     *
     * @param content
     * @param toChatUsername
     * @param messageStatusCallback
     */
    public void sendTxtMessage(String content, String toChatUsername, int chatType, int receiveId, String receiveName,
                               EMCallBack messageStatusCallback) {
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
    }

    /**
     *  发送图片
     * @param list
     * @param toChatUsername
     * @param chatType
     * @param receiveId
     * @param receiveName
     * @param messageStatusCallback
     */
    public void sendImgMessage(List<SendImgBean> list,String toChatUsername, int chatType, int receiveId, String receiveName,
                               EMCallBack messageStatusCallback){
        for (SendImgBean bean:list){
            PublicModel.upLoadChatImg(TokenUtils.getTokenHeader(), bean.getUrl(), new BaseObserver<UpLoadImgBean>() {
                @Override
                protected void onSuccess(UpLoadImgBean data) {
                    EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
                    EMCustomMessageBody customBody = new EMCustomMessageBody(ChatConstant.EXTRA_CUSTOM_IMAGE);
                    message.setAttribute(ChatConstant.EXTRA_IMAGE_PATH, data.getUrl());
                    message.setAttribute(ChatConstant.EXTRA_IMAGE_LOCAL_PATH, bean.getPath());
                    message.setAttribute(ChatConstant.EXTRA_IMAGE_WIDTH, bean.getWidth());
                    message.setAttribute(ChatConstant.EXTRA_IMAGE_HEIGHT, bean.getHeight());
                    message.addBody(customBody);
                    message.setTo(toChatUsername);
                    sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
                }
            });
        }
    }

    /**
     * 发送图片消息
     *
     * @param path
     * @param toChatUsername
     * @param chatType
     * @param messageStatusCallback
     */
    public void sendImgMessage(Activity context, String path, String toChatUsername, int chatType, int receiveId, String receiveName,
                               EMCallBack messageStatusCallback) {
        String url;
        File file = new File(path);
        if (file.exists()) {
            url = file.getPath();
        } else {
            url = FileUtils.getImageAbsolutePath(context, Uri.parse(path));
        }
        PublicModel.upLoadImg(context, TokenUtils.getTokenHeader(), path, new BaseObserver<UpLoadImgBean>() {
            @Override
            protected void onSuccess(UpLoadImgBean data) {

                Bitmap bitmap = BitmapFactory.decodeFile(url);
                int height = bitmap.getHeight();
                int width = bitmap.getWidth();
                LogUtils.i("image", "width:" + width + "    height:" + height);

                EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
                EMCustomMessageBody customBody = new EMCustomMessageBody(ChatConstant.EXTRA_CUSTOM_IMAGE);
                message.setAttribute(ChatConstant.EXTRA_IMAGE_PATH, data.getUrl());
                message.setAttribute(ChatConstant.EXTRA_IMAGE_LOCAL_PATH, path);
                message.setAttribute(ChatConstant.EXTRA_IMAGE_WIDTH, width);
                message.setAttribute(ChatConstant.EXTRA_IMAGE_HEIGHT, height);
                message.addBody(customBody);
                message.setTo(toChatUsername);
                sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
            }
        });

//        Uri uri = Uri.parse(path);
//        EMMessage message = EMMessage.createImageSendMessage(uri, true, toChatUsername);
//        sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
    }
    public void sendVideoMessage(Activity context, String path,String imgPath, String toChatUsername, int chatType, int receiveId, String receiveName,
                               EMCallBack messageStatusCallback) {
        PublicModel.upLoadImg(context, TokenUtils.getTokenHeader(), imgPath, new BaseObserver<UpLoadImgBean>() {
            @Override
            protected void onSuccess(UpLoadImgBean imgBean) {
                PublicModel.upLoadVideo(context, TokenUtils.getTokenHeader(), path, new BaseObserver<UpLoadImgBean>() {
                    @Override
                    protected void onSuccess(UpLoadImgBean data) {
                        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
                        EMCustomMessageBody customBody = new EMCustomMessageBody(ChatConstant.EXTRA_CUSTOM_VIDEO);
                        message.setAttribute(ChatConstant.EXTRA_VIDEO_PATH, data.getUrl());
                        message.setAttribute(ChatConstant.EXTRA_IMAGE_PATH, imgBean.getUrl());
//                        message.setAttribute(ChatConstant.EXTRA_IMAGE_LOCAL_PATH, imgPath);
                        message.setAttribute(ChatConstant.EXTRA_VIDEO_LOCAL_PATH, path);
                        message.setAttribute(ChatConstant.EXTRA_VIDEO_WIDTH, getLocalVideoWidth(path));
                        message.setAttribute(ChatConstant.EXTRA_VIDEO_HEIGHT, getLocalVideoHeight(path));
                        message.setAttribute(ChatConstant.EXTRA_VIDEO_DURATION, getLocalVideoDuration(path));
                        message.addBody(customBody);
                        message.setTo(toChatUsername);
                        sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);

                    }
                });
            }
        });

    }

    public static String getLocalVideoDuration(String filePath) {
        String duration = "0";
        try {
            MediaMetadataRetriever mmr = new  MediaMetadataRetriever();
            mmr.setDataSource(filePath);
            duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);//除以 1000 返回是秒
            //时长(毫秒)
//            String duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
//            //宽
//            String width = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
//            //高
//            String height = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);

        } catch (Exception e) {
            e.printStackTrace();
            return duration;
        }
        return duration;
    }
    public static String getLocalVideoWidth(String filePath) {
        String width = "0";
        try {
            MediaMetadataRetriever mmr = new  MediaMetadataRetriever();
            mmr.setDataSource(filePath);
            //宽
             width = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

        } catch (Exception e) {
            e.printStackTrace();
            return width;
        }
        return width;
    }
    public static String getLocalVideoHeight(String filePath) {
        String height = "0";
        try {
            MediaMetadataRetriever mmr = new  MediaMetadataRetriever();
            mmr.setDataSource(filePath);
            //宽
            height = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);

        } catch (Exception e) {
            e.printStackTrace();
            return height;
        }
        return height;
    }


    /**
     * 发送视频消息
     *
     * @param path
     * @param imgUrl
     * @param toChatUsername
     * @param duration
     * @param chatType
     * @param messageStatusCallback
     */
    public void sendVideoMessage(String path, String imgUrl, String toChatUsername, long duration, int chatType, int receiveId, String receiveName, EMCallBack messageStatusCallback) {
        Uri uri = Uri.parse(path);
        Uri imgUri = Uri.parse(imgUrl);
        EMMessage message = EMMessage.createVideoSendMessage(uri, imgUri, (int) duration, toChatUsername);
        sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
    }

    /**
     * 发送地址消息
     *
     * @param bean
     * @param toChatUsername
     * @param chatType
     * @param receiveId
     * @param receiveName
     * @param messageStatusCallback
     */
    public void sendLocationMessage(GdMapPoiBean bean, String toChatUsername, int chatType, int receiveId, String receiveName, EMCallBack messageStatusCallback) {
        EMMessage message = EMMessage.createLocationSendMessage(bean.getLat(), bean.getLng(), bean.getTitle(), toChatUsername);
        message.setAttribute(ChatConstant.EXTRA_LOCATION_ADDRESS, bean.getAddress());
        sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
    }

    /**
     * 发送语音消息
     *
     * @param path
     * @param length
     * @param toChatUserName
     * @param chatType
     * @param messageStatusCallback
     */
    public void sendVoiceMessage(String path, int length, String toChatUserName, int chatType, int receiveId, String receiveName, EMCallBack messageStatusCallback) {
        EMMessage message = EMMessage.createVoiceSendMessage(Uri.parse(path), length, toChatUserName);
        sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
    }

    /**
     * 发送分享名片消息
     *
     * @param shareName
     * @param shareUserId
     * @param shareHead
     * @param shareNumber
     * @param shareRemark
     * @param toChatUserName
     * @param chatType
     * @param receiveId
     * @param receiveName
     * @param messageStatusCallback
     */
    public void sendShareUserMessage(String shareName, int shareUserId, String shareHead, String shareNumber, String shareRemark,
                                     String toChatUserName, int chatType, int receiveId, String receiveName, EMCallBack messageStatusCallback) {
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        EMCustomMessageBody customBody = new EMCustomMessageBody(ChatConstant.EXTRA_CUSTOM_SHARE);
        message.setAttribute(ChatConstant.EXTRA_CUSTOM_SHARE, ChatConstant.EXTRA_CUSTOM_SHARE);
        message.setAttribute(ChatConstant.EXTRA_SHARE_NICKNAME, shareName);
        message.setAttribute(ChatConstant.EXTRA_SHARE_USERID, shareUserId);
        message.setAttribute(ChatConstant.EXTRA_SHARE_HEAD, shareHead);
        message.setAttribute(ChatConstant.EXTRA_SHARE_NUMBERID, shareNumber);
        message.addBody(customBody);
        message.setTo(toChatUserName);
        sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
    }

    /**
     * 发送撤回消息
     *
     * @param toChatUserName
     * @param chatType
     * @param receiveId
     * @param receiveName
     * @param messageStatusCallback
     */
    public void sendRecallMessage(String toChatUserName, int chatType, int receiveId, String receiveName, EMCallBack messageStatusCallback) {
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        EMCustomMessageBody customBody = new EMCustomMessageBody(ChatConstant.EXTRA_CUSTOM_RECALL);
        message.addBody(customBody);
        message.setTo(toChatUserName);
        sendMessage(message, chatType, receiveId, receiveName, messageStatusCallback);
    }

    /**
     * 发送消息
     *
     * @param message
     * @param messageStatusCallback
     */
    public void sendMessage(EMMessage message, int chatType, int receiveId, String receiveName, EMCallBack messageStatusCallback) {
        if (message == null) {
            ToastUtils.show("消息发送异常，请稍后重试");
            return;
        }
        message.setAttribute(ChatConstant.EXTRA_SEND_USER_ID, UserInfoUtil.getUserId());
//        message.setAttribute(ChatConstant.EXTRA_SEND_USER_HEAD, UserInfoUtil.getUserHead());
        message.setAttribute(ChatConstant.EXTRA_SEND_USER_NICKNAME, UserInfoUtil.getUserNickName());
        message.setAttribute(ChatConstant.EXTRA_RECEIVE_USER_ID, receiveId);
        message.setAttribute(ChatConstant.EXTRA_RECEIVE_USER_NICKNAME, receiveName);
//        message.setAttribute(ChatConstant.EXTRA_RECEIVE_USER_REMARKNAME, receiveRemarkName);
//        message.setAttribute(ChatConstant.EXTRA_RECEIVE_USER_HEAD, receiveHead);
        if (chatType == ChatConstant.CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        }
        message.setMessageStatusCallback(messageStatusCallback);
//        message.setIsNeedGroupAck(true);
        EMClient.getInstance().chatManager().sendMessage(message);
    }


    /**
     * load conversation list
     * <p>
     * 获取最近回话列表
     *
     * @return +
     */
    public List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();

        //添加置顶消息
        List<Pair<Long, EMConversation>> topList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0 && conversation.getExtField().equals("toTop")) {
                    topList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }

        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0 && !conversation.getExtField().equals("toTop")) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(topList);
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        //添加置顶消息
        for (Pair<Long, EMConversation> topItem : topList) {
            list.add(topItem.second);
        }

        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }

        return list;
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

//    /**
//     * 到聊天界面
//     *
//     * @param context
//     * @param hxUsername
//     * @param userId
//     * @param nickName
//     * @param head
//     */
//    public void toChatUi(Context context, String hxUsername, int userId, String nickName, String head) {
//        context.startActivity(new Intent(context, ChatActivity.class)
//                .putExtra(ChatConstant.EXTRA_RECEIVE_USER_HXUSERNAME, hxUsername)
//                .putExtra(ChatActivity.INTENT_USER_ID, userId)
//                .putExtra(ChatActivity.INTENT_USER_NICK_NAME, nickName)
//                .putExtra(ChatActivity.INTENT_USER_HEAD, head));
//
//    }

    /**
     * 到聊天界面
     *
     * @param context
     * @param userInfoBean
     */
    public void toChatUi(Context context, HxUserInfoBean userInfoBean) {
        context.startActivity(new Intent(context, ChatActivity.class)
                .putExtra(ChatActivity.INTENT_HX_USER_INFO, userInfoBean));
    }

    /**
     * 到群聊界面
     *
     * @param context
     * @param userInfoBean
     */
    public void toGroupChatUi(Context context, HxUserInfoBean userInfoBean) {
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra(ChatActivity.INTENT_HX_USER_INFO, userInfoBean);
        intent.putExtra(ChatConstant.CHAT_MESSAGE_TYPE, ChatConstant.CHATTYPE_GROUP);
        context.startActivity(intent);
    }

    /**
     * 转发消息
     *
     * @param msgList
     * @param chatType
     * @param receiveId
     * @param receiveName
     * @param messageStatusCallback
     */
    public void forWardBySelect(Activity activity, List<EMMessage> msgList, String toChatUsername, int chatType, int receiveId, String receiveName, EMCallBack messageStatusCallback) {
        for (int i = 0; i < msgList.size(); i++) {
            EMMessage message = msgList.get(i);
            if (message.getType() == EMMessage.Type.VOICE) {
                LogUtils.d("无法转发语音消息");
                continue;
            }
            if (message.getType() == EMMessage.Type.CUSTOM) {
                EMCustomMessageBody body = (EMCustomMessageBody) message.getBody();
                if (body.event().equals(ChatConstant.EXTRA_CUSTOM_SHARE)) {
                    LogUtils.d("无法转发名片消息");
                    continue;
                }
                if (body.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) { // 转发自定义图片消息
                    try {
                        String path = message.getStringAttribute(ChatConstant.EXTRA_IMAGE_PATH);
                        String localPath = message.getStringAttribute(ChatConstant.EXTRA_IMAGE_LOCAL_PATH);
                        if (message.direct() == EMMessage.Direct.SEND) {
                            File file = new File(localPath);
                            if (file.exists()) {
                                sendImgMessage(activity, localPath, toChatUsername, chatType, receiveId, receiveName, messageStatusCallback);
                            } else {
                                ToastUtils.show("图片地址已损坏");
                            }
                        } else {
                            DownLoadUtil.downLoadImg(path, new DownLoadUtil.OnDownLoadListener() {
                                @Override
                                public void success(String path) {
                                    sendImgMessage(activity, path, toChatUsername, chatType, receiveId, receiveName, messageStatusCallback);
                                }

                                @Override
                                public void fail() {

                                }
                            });
                        }
                    } catch (Exception e) {
                        e.getMessage();
                        continue;
                    }
                }
                if (body.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)) { // 转发自定义视频消息
                    try {
                        String path = message.getStringAttribute(ChatConstant.EXTRA_VIDEO_PATH);
                        String imgPath = message.getStringAttribute(ChatConstant.EXTRA_IMAGE_PATH);
                        String videoPath = message.getStringAttribute(ChatConstant.EXTRA_VIDEO_LOCAL_PATH);

                        EMMessage newMessage = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
                        EMCustomMessageBody customBody = new EMCustomMessageBody(ChatConstant.EXTRA_CUSTOM_VIDEO);
                        newMessage.setAttribute(ChatConstant.EXTRA_VIDEO_PATH, path);
                        newMessage.setAttribute(ChatConstant.EXTRA_IMAGE_PATH, imgPath);
//                        newMessage.setAttribute(ChatConstant.EXTRA_IMAGE_LOCAL_PATH, imgPath);
                        newMessage.setAttribute(ChatConstant.EXTRA_VIDEO_LOCAL_PATH, videoPath);
                        newMessage.setAttribute(ChatConstant.EXTRA_VIDEO_WIDTH, getLocalVideoWidth(path));
                        newMessage.setAttribute(ChatConstant.EXTRA_VIDEO_HEIGHT, getLocalVideoHeight(path));
                        newMessage.setAttribute(ChatConstant.EXTRA_VIDEO_DURATION, getLocalVideoDuration(path));
                        newMessage.addBody(customBody);
                        newMessage.setTo(toChatUsername);
                        sendMessage(newMessage, chatType, receiveId, receiveName, messageStatusCallback);
                    } catch (Exception e) {
                        e.getMessage();
                        continue;
                    }
                }
            }
            if (message.getType() == EMMessage.Type.TXT) {
                EMTextMessageBody body = (EMTextMessageBody) message.getBody();
                sendTxtMessage(body.getMessage(), toChatUsername, chatType, receiveId, receiveName, messageStatusCallback);
            } else if (message.getType() == EMMessage.Type.LOCATION) {
                try {
                    EMLocationMessageBody body = (EMLocationMessageBody) message.getBody();
                    GdMapPoiBean bean = new GdMapPoiBean();
                    bean.setLng(body.getLongitude());
                    bean.setLat(body.getLatitude());
                    bean.setTitle(body.getAddress());
                    bean.setAddress(message.getStringAttribute(ChatConstant.EXTRA_LOCATION_ADDRESS));
                    sendLocationMessage(bean, toChatUsername, chatType, receiveId, receiveName, messageStatusCallback);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (message.getType() == EMMessage.Type.IMAGE) {
                EMImageMessageBody imgBody = (EMImageMessageBody) message.getBody();
                if (message.direct() == EMMessage.Direct.SEND) {
                    File file = new File(imgBody.getLocalUri().getPath());
                    if (file.exists()) {
                        sendImgMessage(activity, imgBody.getLocalUri().getPath(), toChatUsername, chatType, receiveId, receiveName, messageStatusCallback);
                    } else {
                        ToastUtils.show("图片地址已损坏");
                    }
                } else {
                    String uri = imgBody.getRemoteUrl();
                    ELoad eload = new ELoad.Builder(MyApplication.getContext())
                            .addDownloadTaskListener(new DownloadTask.DownloadTaskListener() {
                                @Override
                                public void onDownloadTaskPrepare(DownloadTask task, Observable<ResponseBody> observable) {

                                }

                                @Override
                                public void onDownloadTaskStart(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskPause(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskResume(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskError(DownloadTask task, Throwable e) {
                                    LogUtils.d("下载错误:" + e.getMessage());
                                }

                                @Override
                                public void onDownloadTaskComplete(DownloadTask task) {
                                    String path = task.getEntity().getFilePath() + "/" +
                                            task.getEntity().getFileName();
                                    LogUtils.d("下载完成：" + path);
                                    sendImgMessage(activity, path, toChatUsername, chatType, receiveId, receiveName, messageStatusCallback);
                                }

                                @Override
                                public void onDownloadTaskCancel(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskReset(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskRecycle(DownloadTask task, TaskRecycler taskRecycler) {

                                }
                            }).build();
                    //可以当成一个Request
                    DownloadTask task = eload.url(uri).create();
                    task.start();
                }
            }
        }
    }
}
